package com.xianl.busiplat.mybatis.dialect;


public class OracleDialect implements Dialect{

	public String getLimitString(String sql, boolean hasOffset){
		sql = sql.trim();
		boolean isForUpdate = false;
		if (sql.toLowerCase().endsWith(" for update")) {
			sql = sql.substring(0, sql.length() - 11);
			isForUpdate = true;
		}

		StringBuffer pagingSelect = new StringBuffer(sql.length() + 100);
		if (hasOffset) {
			pagingSelect
					.append("select * from ( select row_.*, rownum rownum_ from ( ");
		} else {
			pagingSelect.append("select * from ( ");
		}
		pagingSelect.append(sql);
		if (hasOffset) {
			pagingSelect.append(" ) row_ ) where rownum_ <= ? and rownum_ > ?");
		} else {
			pagingSelect.append(" ) where rownum <= ?");
		}

		if (isForUpdate) {
			pagingSelect.append(" for update");
		}
		return pagingSelect.toString();
	}

	public String getLimitString(String sql, int offset, int limit){
		boolean hasOffset = true;

		StringBuffer pagingSelect = new StringBuffer(sql.length() + 100);

		pagingSelect
				.append("select * from ( select row_.*, rownum rownum_ from ( ");

		pagingSelect.append(sql);

		pagingSelect.append(" ) row_ ) ");

		// add the restriction to the outer select
		if (hasOffset) {
			pagingSelect.append(" where rownum_ > " + offset
					+ " and rownum_ < =" + (offset + limit));
		}

		return pagingSelect.toString();
	}

	public boolean supportsLimit(){
		return true;
	}
}
